import { apiLogOut } from '@/http/api/login';
import { eLocalStorageConfig } from '@/interface/elocal_storage';

import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { useMenus } from './menus';
import { routers } from '@/router';

export const useUserInfo = defineStore('userInfo', {
    state: () =>
        <{ user: any | null, token: string }>{
            user: localStorage.getItem(eLocalStorageConfig.USER_INFO) ? JSON.parse(localStorage.getItem(eLocalStorageConfig.USER_INFO)!) : null,
            token: localStorage.getItem(eLocalStorageConfig.TOKEN) || ""
        },
    actions: {
        setUserInfo(data: any | null) {
            this.user = data;
        },
        async logOut() {
            try {
                await apiLogOut();
                useMenus().$reset();
                this.user = null;
            } catch (error) {
                message.error((error as any).msg || '退出失败');
                useRouter().push({
                    name: "login"
                });
            }
        },
        async checkLogin() {
            // try {
            //     const res = await checkLoginStatus();
            //     this.setUserInfo(res.data);
            // } catch (error) {
            //     this.user = null;
            // }
        },
    },
    getters: {
        getToken(): string | null {
            const str = this.user?.user_token || localStorage.getItem(eLocalStorageConfig.TOKEN);
            return str;
        },
    },
});

useUserInfo().$subscribe((_, state) => {
    if (state.user) {
        localStorage.setItem(eLocalStorageConfig.USER_INFO, JSON.stringify(state.user));
        localStorage.setItem(eLocalStorageConfig.TOKEN, state.user.user_token);
        state.token = state.user.user_token;
    } else {
        localStorage.removeItem(eLocalStorageConfig.USER_INFO);
        localStorage.removeItem(eLocalStorageConfig.TOKEN);
        state.token = "";
    }
    console.log(333333);
    
    if (!state.token) {
        console.log("跳转login");
        
        routers.push({ name: "login" })
    }
});
